import { getChatResponse } from "@/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useState } from "react";
import ReactMarkdown from "react-markdown";

function HtmlRender({ html }: { html: string }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

const ChatInterface = () => {
  const [messages, setMessages] = useState<
    Array<{
      role: "user" | "assistant";
      content: string;
    }>
  >([]);
  // const [input, setInput] = useState('你好，头疼怎么办？')
  const [input, setInput] = useState("你是谁!");

  function uploadFiles() {
    const fileInput = document.getElementById(
      "fileInput"
    ) as HTMLInputElement | null;
    if (!fileInput || !fileInput.files) return;

    const formData = new FormData();

    for (let i = 0; i < fileInput.files.length; i++) {
      formData.append("files", fileInput.files[i]);
    }

    fetch("/api/upload", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("上传成功:", data);
      })
      .catch((error) => {
        console.error("上传失败:", error);
      });
  }

  const onChat = async () => {
    if (!input.trim()) return;
    // 深度拷贝messages
    let messagesCopy = JSON.parse(JSON.stringify(messages));
    messagesCopy.push({ role: "user", content: input });
    setMessages(messagesCopy);

    getChatResponse({
      text: input,
      max_length: 1000,
    }).then(
      (res: any) => {
        console.log(res);
        messagesCopy.push({
          role: "assistant",
          content: (res.data as any).generated_text,
        });
        setMessages(messagesCopy);
        setInput("");
      },
      (err: any) => {
        console.error(err);
      }
    );
  };

  return (
    <div className="flex h-screen flex-col">
      {/* 头部 */}
      <header className="border-b p-4">
        <h1 className="text-xl font-semibold">药学咨询</h1>
      </header>

      {/* 聊天区域 */}
      <ScrollArea className="flex-1 p-4">
        <div className="space-y-4">
          {messages.map((message, i) => (
            <div
              key={i}
              className={`flex ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
            >
              <div
                className={`rounded-lg p-4 max-w-[80%] ${
                  message.role === "user"
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted"
                }`}
              >
                <HtmlRender html={message.content} />
              </div>
            </div>
          ))}
        </div>
      </ScrollArea>

      {/* 输入区域 */}
      <div className="border-t p-4">
        <div className="flex gap-2">
          <Input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="输入您的问题..."
            className="flex-1"
          />
          <Button onClick={onChat}>发送</Button>
        </div>
      </div>
    </div>
  );
};

export default ChatInterface;
